<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Requests\HeartLog\Store;
use App\Models\Device;
use App\Models\HeartLog;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class HeartLogController extends Controller
{
    protected $result = ['code' => 1, 'msg' => ''];
    const FINAL_CODE = 0;
    const DEVICE_UNREGISTER_CODE = 200;
    const DATA_VALIDATE_FAIL_CODE = 300;
    const UNKNOWN_ERROR = -1;

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
//        $models = HeartLog::paginate(1);
//        return $models;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Store $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Store $request)
    {
        $validated = $request->validated();
        $validated = array_combine(
            [
                'device_id',
                'created_at',
                'soc',
                'card_list',
            ], $validated
        );
        $device = Device::query()->firstOrCreate(['device_id' => $validated['device_id']]);

        $validated['local_device_id'] = $device->id;
        $validated['card_list'] = json_encode($validated['card_list']);
        $model = HeartLog::query()->create($validated);
        if ($model) {
            $this->result = ['code' => self::FINAL_CODE, 'msg' => '成功', 'data' => [$model]];
        } else {
//            Log::debug($model);
        }
        return response()->json($this->result);

    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     */
    public function show($id)
    {
        return HeartLog::query()->findOrFail($id);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
